import Cookies from 'js-cookie'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import Vue from 'vue'
import { RTFJS } from "rtf.js";
import api from '@/api/utils'
Vue.use(Vuex)
import i18n from '../i18n'
let url =
  process.env.NODE_ENV == 'development'
    ? 'http://8.138.252.96:48080'
    : 'https://www.rebirthealth.com'
// 针对需要Cookie存储的模块
const cookieStorage = createPersistedState({
  key: 'vuex-cookie',
  paths: ['token', 'refToken'], // 指定要持久化的模块路径
  storage: {
    getItem: (key) => Cookies.get(key),
    setItem: (key, value) => Cookies.set(key, value, { expires: 7 }), // 7天过期
    removeItem: (key) => Cookies.remove(key),
  },
})

// 针对需要localStorage存储的模块
const localStorage = createPersistedState({
  key: 'vuex-session',
  paths: ['userInfo', 'userId', 'areaTree', 'configData', 'personTab'], // 指定要持久化的模块路径
  storage: window.localStorage,
})

export default new Vuex.Store({
  plugins: [cookieStorage, localStorage],

  state: {
    baseURL: url,
    userInfo: null,
    token: null,
    refToken: null,
    userId: null,
    resetBy: null,
    resetPhone: null,
    resetCode: null,
    areaTree: null,
    configData: null,
    personTab: 0,
    serveContent: null
  },
  getters: {
    isExpert: (state) => {
      let userInfo = state.userInfo
      if (userInfo) {
        userInfo = JSON.parse(userInfo)
        let groupIds = userInfo.groupIds
        // 如果包含1-普通用户
        // 如果包含2-推广者
        // 如果包含3-专家
        if (groupIds.includes(3)) {
          return true
        }
      }
      return false
    },
    isPutong: (state) => {
      let userInfo = state.userInfo
      if (userInfo) {
        userInfo = JSON.parse(userInfo)
        let groupIds = userInfo.groupIds
        // 如果包含1-普通用户
        // 如果包含2-推广者
        // 如果包含3-专家
        if (groupIds.includes(1)) {
          return true
        }
      }
      return false
    },
    isTuiguang: (state) => {
      let userInfo = state.userInfo
      if (userInfo) {
        userInfo = JSON.parse(userInfo)
        let groupIds = userInfo.groupIds
        // 如果包含1-普通用户
        // 如果包含2-推广者
        // 如果包含3-专家
        if (groupIds.includes(2)) {
          return true
        }
      }
      return false
    },
  },
  mutations: {
    SET_PERSONTAB(state, index) {
      state.personTab = index
    },
    SET_USER(state, user) {
      state.userInfo = JSON.stringify(user)
      // setSession("communityUser", JSON.stringify(user));
    },
    DEL_USER(state) {
      state.userInfo = null
    },
    SET_TOKEN(state, token) {
      state.token = token
      // setSession("communityUser", JSON.stringify(user));
    },
    DEL_TOKEN(state) {
      state.token = null
    },
    SET_REF_TOKEN(state, token) {
      state.refToken = token
      // setSession("communityUser", JSON.stringify(user));
    },
    DEL_REF_TOKEN(state) {
      state.refToken = null
    },
    SET_USERID(state, userId) {
      state.userId = userId
      // setSession("communityUser", JSON.stringify(user));
    },
    DEL_USERID(state) {
      state.userId = null
    },
    SET_REGION_TREE(state, data) {
      state.areaTree = data
    },
    SET_CONFIG(state, data) {
      state.configData = data
    },
    SET_TIMER(state, timer) {
      state.timer = timer
    },
    DEL_TIMER(state) {
      if (state.timer) {
        clearInterval(state.timer)
        state.timer = null
      }
    },
    SET_SERVE_CONTENT(state, serveContent) {
      state.serveContent = serveContent
    },
  },
  actions: {
    async loadRegionTree({ state, commit }) {
      // 1. 先尝试从本地存储读取
      const cachedData = ''
      if (!cachedData) {
        try {
          // 2. 本地没有则调用接口
          const res = await Vue.prototype.$http.get(api.getAreaTree)
          if (res && res.code == 0) {
            commit('SET_REGION_TREE', res.data)
          } else {
            Vue.prototype.$message.error(i18n.t('获取地区树失败:') + res.msg)
          }
        } catch (error) {
          console.error(i18n.t('获取地区树失败:'), error)
          throw error
        }
      }
    },
    async getConfigData({ state, commit }) {
      // 1. 先尝试从本地存储读取
      const cachedData = ''
      if (!cachedData) {
        try {
          // 2. 本地没有则调用接口
          const res = await Vue.prototype.$http.get(api.getConfig)
          if (res && res.code == 0) {
            commit('SET_CONFIG', res.data)
          } else {
            Vue.prototype.$message.error(i18n.t('获取基础配置失败:') + res.msg)
          }
        } catch (error) {
          console.error(i18n.t('获取基础配置失败:'), error)
          throw error
        }
      }
    },
    // async initServeContent({ state, commit }) {
    //   try {
    //     // 1. 使用 fetch 加载 public 目录下的文件
    //     const response = await fetch("./protocol_index.html"); // 路径相对于 public 目录
    //     if (!response.ok) throw new Error("文件加载失败");

    //     // 2. 转换为 ArrayBuffer
    //     const arrayBuffer = await response.arrayBuffer();
    //     // 3. 用 RTF.js 解析
    //     const rtf = new RTFJS.Document(arrayBuffer);

    //     const serveContent = await rtf.render();
    //     commit('SET_SERVE_CONTENT', serveContent)
    //   } catch (error) {
    //     console.error("RTF 解析失败:", error);
    //   }
    // },
  },
})
